package com.jiadakeji.ppm.common.requestvalidator;


import com.jiadakeji.ppm.api.common.JsonResult;
import com.jiadakeji.ppm.common.utils.Reflections;
import com.jiadakeji.ppm.common.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 注解处理判断参数是否为空
 * @author HHAOYU
 * @version 2018-08-17
 */

@Component
@Aspect
public class ReqNotNullAspect {


    //切入点名称
    @Pointcut(value = "@annotation(ReqNotNull)",argNames = "ReqNotNull")
    private void ReqNotNullPointcut(ReqNotNull reqNotNull) {
    }


    @Around( "ReqNotNullPointcut(reqNotNull)")
    public Object velidator(ProceedingJoinPoint joinPoint, ReqNotNull reqNotNull){
        JsonResult<Object> result = new JsonResult<>();
        //获取切入点函数参数列表
        Object[] args = joinPoint.getArgs();
        //获取第一个参数，习惯行为（json传入参数一般在第一个）
        Object arg =  args[0];

        //获取注解中填入的值
        String notNullString = reqNotNull.value();
        Class t = reqNotNull.clazz();
        String [] notNullParams = notNullString.split(",");
        for (String notNullparam:notNullParams) {
            //去除空格
            notNullparam = notNullparam.replaceAll(" ","");
            // 反射工具获取需要判断的传入字段
            Object va = Reflections.invokeGetter(arg,notNullparam);
            //若为string则判断是否为null或者为空
            //其他的直接判断是否为null
            if(va instanceof String){
                if(StringUtils.isBlank((String)va)){
                    return result.setCodeAndMessage(-1,notNullparam+"不能为空");
                }
            }else {
                if(null == va){
                    return result.setCodeAndMessage(-1,notNullparam+"不能为空");
                }
            }
        }

        try {
             result = (JsonResult<Object>) joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result ;
    }




}
